package com.fhnew.app.ui.activity.recomend.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fhnew.app.R;
import com.fhnew.app.global.Constants;
import com.fhnew.app.model.CustomObserver;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.model.network.HttpJsonUtils;
import com.fhnew.app.model.network.entity.req.ResTeamlist;
import com.fhnew.app.ui.dialogactivity.RegisterDialog;

import com.fhnew.app.util.DoubleDatePickerDialog;
import com.fhnew.app.widget.MyRecyclerView;
import com.fhnew.app.util.OnEndLessScrollListener;
import com.fhnew.app.util.OnItemClickListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2019/10/11.
 */

public class TeamListFragment extends Fragment {

    private ArrayList<ResTeamlist.DataBean> dataBeans = new ArrayList<>();
    private ArrayList<ResTeamlist.UserLevelBean> userLevelBeans = new ArrayList<>();
    private Adapter adapter;

    private EditText teamid;
    private EditText leaderteamid;
    private TextView teamstarttime;
    private TextView teamendtime;
    private TextView teamsearch;
    private TextView teamclear;
    private TextView sigupregbt;
    private MyRecyclerView teamlist1;
    private String starttime;
    private String endtime;

    private String userAccount;//成员账号
    private String leaderid;//上级账号

    private int page;//初始页数

    private OnEndLessScrollListener onEndLessScrollListener;


    private void initView (View view) {
        teamid = view.findViewById(R.id.teamid);
        leaderteamid = view.findViewById(R.id.leaderteamid);
        teamstarttime = view.findViewById(R.id.teamstarttime);
        teamendtime = view.findViewById(R.id.teamendtime);
        teamsearch = view.findViewById(R.id.teamsearch);
        teamclear = view.findViewById(R.id.teamclear);
        sigupregbt = view.findViewById(R.id.sigupregbt);
        teamlist1 = view.findViewById(R.id.teamlist1);

        teamstarttime.setOnClickListener(onClickListener);
        teamendtime.setOnClickListener(onClickListener);
        teamsearch.setOnClickListener(onClickListener);
        teamclear.setOnClickListener(onClickListener);

    }

    @Nullable
    @Override
    public View onCreateView (@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        container = (ViewGroup) inflater.inflate(R.layout.teamlistlayout, null);
        initView(container);
        return container;
    }

    @Override
    public void onViewCreated (@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化控件
        teamlist1.setNestedScrollingEnabled(false);
        page = 1;


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        onEndLessScrollListener = new OnEndLessScrollListener(linearLayoutManager) {
            @Override
            public void getMoreData (int currentPage) {
                //下拉加载的时候页数加1
                searchcommission(++page);
            }
        };
        teamlist1.setLayoutManager(linearLayoutManager);


        adapter = new Adapter();
        teamlist1.setAdapter(adapter);
        //添加滑动监听
        teamlist1.addOnScrollListener(onEndLessScrollListener);
        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
        sdf.applyPattern("yyyy-MM-dd");// a为am/pm的标记
        Date date = new Date();// 获取当前时间
        starttime = sdf.format(date);
        endtime = sdf.format(date);
        sigupregbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick (View v) {
                startActivity(new Intent(getContext(), RegisterDialog.class));
            }
        });
    }

    //结束时间后传参为    上级账号     成员账号   会员等级
    private void searchcommission (int page) {
        HttpJsonUtils.getHttpApiInstance()
                .getteamlist(Constants.getuseAdress() + "api/m/promotion/teamlist", page + "", "10", starttime, endtime,
                        userAccount, leaderid, "", UserModel.Token).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new CustomObserver<ResTeamlist>(TeamListFragment.this) {
                .subscribe(new CustomObserver<ResTeamlist>() {
                    @Override
                    protected void onCustomNext (ResTeamlist resTeamlist) {
                        if (resTeamlist.code == 0 && resTeamlist.data.size() > 0 && dataBeans.size() < 10) {
                            dataBeans.clear();
                            dataBeans.addAll(resTeamlist.data);
                            userLevelBeans.clear();
                            userLevelBeans.addAll(resTeamlist.userLevel);
                            adapter.notifyDataSetChanged();
                        } else if (resTeamlist.code == 0 && resTeamlist.data.size() > 0 && dataBeans.size() > 9) {
                            dataBeans.addAll(resTeamlist.data);
                            adapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom (Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom (Throwable e) {

                    }
                });

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            switch (view.getId()) {
                case R.id.teamstarttime:
                    Calendar c = Calendar.getInstance();
                    new DoubleDatePickerDialog(getContext(), 0, new DoubleDatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet (DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                               int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear,
                                               int endDayOfMonth) {
                            teamstarttime.setText("开始时间：" + startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth);
                            starttime = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
                        }
                    }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), false).show();
                    break;
                case R.id.teamendtime:
                    Calendar c2 = Calendar.getInstance();
                    new DoubleDatePickerDialog(getContext(), 0, new DoubleDatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet (DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                               int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear,
                                               int endDayOfMonth) {
                            teamendtime.setText("结束时间：" + startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth);
                            endtime = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
                        }
                    }, c2.get(Calendar.YEAR), c2.get(Calendar.MONTH), c2.get(Calendar.DATE), false).show();
                    break;
                case R.id.teamsearch:
                    if (TextUtils.isEmpty(teamid.getText().toString()) && TextUtils.isEmpty(leaderteamid.getText().toString())) {
                        userAccount = teamid.getText().toString();
                        leaderid = leaderteamid.getText().toString();
                    } else {
                        userAccount = "";
                        leaderid = "";
                    }
                    searchcommission(page);
                    break;
                case R.id.teamclear:
                    starttime = "";
                    endtime = "";
                    adapter.notifyDataSetChanged();
                    teamstarttime.setText("开始时间");
                    teamendtime.setText("结束时间");
                    break;
            }
        }
    };


    class Adapter extends RecyclerView.Adapter<Adapter.MViewHolder>
            implements OnItemClickListener {
        @NonNull
        @Override
        public Adapter.MViewHolder onCreateViewHolder (@NonNull ViewGroup viewGroup, int viewType) {
            return new Adapter.MViewHolder(LayoutInflater.from(getContext())
                    .inflate(R.layout.teamlistitem, viewGroup, false));
        }


        @Override
        public void onBindViewHolder (@NonNull MViewHolder holder, int postion) {
            if (postion % 2 != 0) {
                holder.teamitem.setBackgroundResource(R.color.blue);
            } else {
                holder.teamitem.setBackgroundResource(R.color.royalblue);
            }
            holder.teamlistname.setText("" + dataBeans.get(postion).user_account);
            holder.teamlistelever.setText("" + dataBeans.get(postion).user_level);
            holder.teamleader.setText("" + dataBeans.get(postion).promoter_account);
            holder.teammoney.setText("" + dataBeans.get(postion).user_money);
            holder.teamlistname.setText("" + dataBeans.get(postion).user_account);
            String str = dataBeans.get(postion).user_createdTime.substring(0, 10);
            holder.teamrigisttime.setText("" + str);
            String str1 = dataBeans.get(postion).user_lastLoginTime.substring(0, 10);
            holder.teamlogintime.setText("" + str1);
        }


        @Override
        public int getItemCount () {
            return dataBeans.size();
        }

        @Override
        public void onItemClick (View view, int position) {

        }

        public class MViewHolder extends RecyclerView.ViewHolder {
            LinearLayout teamitem;
            TextView teamlistname, teamlistelever, teamleader, teammoney, teamrigisttime, teamlogintime;

            MViewHolder (View itemView) {
                super(itemView);
                teamitem = (LinearLayout) itemView.findViewById(R.id.teamitem);
                teamlistname = (TextView) itemView.findViewById(R.id.teamlistname);
                teamlistelever = (TextView) itemView.findViewById(R.id.teamlistelever);
                teamleader = (TextView) itemView.findViewById(R.id.teamleader);
                teammoney = (TextView) itemView.findViewById(R.id.teammoney);
                teamrigisttime = (TextView) itemView.findViewById(R.id.teamrigisttime);
                teamlogintime = (TextView) itemView.findViewById(R.id.teamlogintime);
            }
        }
    }
}
